package com.shixun.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baidubce.model.User;
import com.shixun.dao.BaseDao;
import com.shixun.dao.FcbDao;
import com.shixun.entity.FileEntity;
import com.shixun.entity.FpinglunEntity;
import com.shixun.entity.UserEntity;
import org.omg.CORBA.OBJ_ADAPTER;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * Created by fan-computer on 2016/12/13.
 */
@Service("FcbService")
public class FcbServiceImpl implements FcbService {
    @Autowired
    private FcbDao fcbDao;
    @Autowired
    private FileEntity fileEntity;
    @Autowired
    private FpinglunEntity fpinglunEntity;
    @Autowired
    private UserEntity userEntity;

    /**
     * 注册
     *
     * @param userEntity
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public boolean userregisterService(UserEntity userEntity) {
        if (fcbDao.serchUser(userEntity.getLoginId()).size() > 0) {
            return false;
        } else {
            userEntity.setCreatetime(new Timestamp(System.currentTimeMillis()));
            userEntity.setLoginPass(BaseDao.userPasswordMD5(userEntity.getLoginPass()));
            userEntity.setState("1");   //有效用户状态为1
            fcbDao.addForBuser(userEntity);
            return true;
        }
    }

    /**
     * 登录
     *
     * @param userEntity
     * @return
     * @throws Exception
     */
    @Override
    public boolean userloginService(UserEntity userEntity) {
        System.out.println("%%%%%%%%%%%%%%%%%%%%%" + userEntity.toString());
        List<Object> list = fcbDao.serchUser(userEntity.getLoginId());
        if (list.size() > 0) {
            UserEntity user1 = (UserEntity) list.get(0);
            if (BaseDao.userPasswordMD5(userEntity.getLoginPass()).equals(user1.getLoginPass())) {
                BaseDao.getSessions().put("user", list.get(0));
                return true;
            }
            return false;
        }
        return false;
    }


    /**
     * 发表帖子
     *
     * @param fileEntity
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public boolean saveFileService(FileEntity fileEntity) {
        if (fileEntity == null) {
            return false;
        } else {
            fileEntity.setUserEntity((UserEntity) BaseDao.getSessions().get("user"));
            fileEntity.setFtime(new Timestamp(System.currentTimeMillis()));
            fileEntity.setCreatetime(new Timestamp(System.currentTimeMillis()));
            fileEntity.setFnumber("0");      //评论数量
            fileEntity.setFdianzan("0");    //点赞数
            fileEntity.setMore1("0");      //0为帖子    1为文章
            fileEntity.setState("1");     //帖子状态
            fileEntity.setMore2("1");    //帖子的浏览量
            fcbDao.postTiezi(fileEntity);
            return true;
        }
    }

    /**
     * 获取发表的帖子
     *
     * @return
     */
    @Override
    public List<FileEntity> getTiezi() {
        List<Object> list = fcbDao.searchTiezi();
        if (list.size() > 0) {
            List<FileEntity> data = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                data.add((FileEntity) list.get(i));
            }
            return data;
        }
        return null;
    }


    /**
     * 删除帖子
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public boolean deleteTiezi(String string) {
        if ("".equals(string) || string == null) {
            return false;
        } else {
            List<Object> fileEntities = fcbDao.searchOneTiezi(string);
            if (fileEntities.size() > 0) {
                if (fcbDao.delete_tiezi((FileEntity) fileEntities.get(0))) {
                    System.out.println("删除成功");
                    return true;
                }
                return false;
            }
            return false;
        }
    }


    /**
     * 加載更多帖子信息
     *
     * @return
     */
    @Override
    public List<FileEntity> searchAllFileService() {
        List<Object> listAll = fcbDao.searchFileDao();
        if (listAll.size() > 0) {
            List<FileEntity> list = new ArrayList<>();
            for (int i = 0; i < listAll.size(); i++) {
                list.add((FileEntity) listAll.get(i));
            }
            return list;
        }
        return null;
    }


    /**
     * 通过id获得每一条帖子的具体内容
     *
     * @param st
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public FileEntity searchOneTieziService(String st) {
        if ("".equals(st) || st == null) {
            return null;
        } else {
            FileEntity fileEntity = (FileEntity) fcbDao.searchOneTiezi(st).get(0);
            fileEntity.setMore2(BaseDao.returnAddyi(fileEntity.getMore2()));
            return fileEntity;
        }
    }

    /**
     * 对帖子点赞
     *
     * @param string
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void saveDianzan(String string) {
        BaseDao.getResponse().setCharacterEncoding("utf-8");
        JSONObject jsonObject = new JSONObject();
        if ("".equals(string) || string == null) {
            jsonObject.put("code", "未获取到数据");
        } else {
            List<Object> objects = fcbDao.searchPinglun(string);
            if (objects.size() > 0) {
                jsonObject.put("code", "您已经点过，请不要重复点赞！");
            } else {
                fcbDao.saveDianzan(string);
                //对相对应的文件点赞列加一
                FileEntity fileEntity = (FileEntity) fcbDao.searchOneTiezi(string).get(0);
                fileEntity.setFdianzan(BaseDao.returnAddyi(fileEntity.getFdianzan()));
                jsonObject.put("code", "感谢您的点赞");
            }
        }
        try {
            BaseDao.getResponse().getWriter().write(jsonObject.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 发表评论
     *
     * @param str1
     * @param str2
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void PostPinglun(String str1, String str2) {
        BaseDao.getResponse().setCharacterEncoding("utf-8");
        if ("".equals(str1) || str1 == null || "".equals(str2) || str2 == null) {
            try {
                BaseDao.getResponse().getWriter().write(JSON.toJSONString("网络出现问题，请稍后再试"));
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            fcbDao.tieziPinglun(str1, str2);
            FileEntity fileEntity = (FileEntity) fcbDao.searchOneTiezi(str1).get(0);
            fileEntity.setFnumber(BaseDao.returnAddyi(fileEntity.getFnumber()));
            List<Object> list = fcbDao.findPinglun(str1);
            List<FpinglunEntity> list1 = new ArrayList<>();
            if (list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    if (((FpinglunEntity) list.get(i)).getMore1().equals("00")) {
                        list1.add((FpinglunEntity) list.get(i));
                    }
                }

                List<Map> mapList = new ArrayList<>();
                for (FpinglunEntity pinglun : list1) {
                    mapList.add(pinglun.toMap());
                }
                String result = JSON.toJSONString(mapList);
                System.out.println("#######" + result);
                try {
                    BaseDao.getResponse().getWriter().write(result);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 查找所有评论
     * @param string
     * @return
     */
    @Override
    public List<FpinglunEntity> getAllPinglun(String string) {
        if ("".equals(string) || string == null){
            return  null;
        }else {
            List<Object> list = fcbDao.findPinglun(string);
            List<FpinglunEntity> alist = new ArrayList<>();
            for (int i = 0;i<list.size();i++){
                alist.add((FpinglunEntity) list.get(i));
            }
            return alist;
        }
    }




    /**
     * 在后台管理中心通过ID查看文章
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public FileEntity findArticle(String string) {
        if ("".equals(string) || string == null){
            return null;
        }else {
            FileEntity fileEntity = (FileEntity) fcbDao.findArticle(string).get(0);
            return fileEntity;
        }
    }


    /**
     * 通过ID删除后台管理中心中的文章
     * @param string
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public boolean deleteArticleService(String string) {
        if ("".equals(string) || string == null){
            return false;
        }else {
//            fileEntity.setId(string);
            fcbDao.deleteArticleDao(string);
            return true;
        }
    }


    /**
     * 后台管理中心查看帖子
     * @param string
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public FileEntity findTiezi(String string) {
        if ("".equals(string) || string == null){
            return null;
        }else {
           FileEntity fileEntity = (FileEntity) fcbDao.findTiezi(string).get(0);
            return fileEntity;
        }

    }


    /**
     * 后台管理中心删除帖子
     * @param string
     * @return
     */
    @Override
    public boolean deleteTieziService(String string) {
        if ("".equals(string) || string == null){
            return false;
        }else {
            fcbDao.deleteTieziDao(string);
            return true;
        }
    }
}
